﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Web;

namespace DynamicDNS.Enom
{
    public class EnomService: IGatewayService
    {
        public UriBuilder Url;
        public EnomService(string url)
        {
            Url = new UriBuilder(url);
        }
        public XmlDocument Response(Command command)
        {
            var collection = command.Collection;
            Url.Query = ToQueryString(collection);
            var response = new XmlDocument();
            response.Load(Url.ToString());
            return response;
        }

        private string ToQueryString(NameValueCollection collection)
        {
            var builder = new StringBuilder();
            for(var i=0; i< collection.Keys.Count;i++)
             if(!string.IsNullOrEmpty(collection.Keys[i]))
                 foreach(var value in collection[collection.Keys[i]].Split(','))
                     builder.Append((builder.Length==0)?"":"&")
                         .Append(HttpUtility.UrlEncode(collection.Keys[i]))
                         .Append("=")
                         .Append(value);
            return builder.ToString();    
        }
    }
}
